# To use Inference Engine backend, specify location of plugins:
# export LD_LIBRARY_PATH=/opt/intel/deeplearning_deploymenttoolkit/deployment_tools/external/mklml_lnx/lib:$LD_LIBRARY_PATH
import cv2
import numpy as np
import argparse
import math
import time
from funtion import vector_centerpoint
from funtion import similarity
from funtion import video_brodcast
# #动作识别
# parser = argparse.ArgumentParser()
# parser.add_argument('--input', help='Path to image or video. Skip to capture frames from camera')
# parser.add_argument('--thr', default=0.2, type=float, help='Threshold value for pose parts heat map')
# parser.add_argument('--width', default=368, type=int, help='Resize input to specific width.')
# parser.add_argument('--height', default=368, type=int, help='Resize input to specific height.')

def Init2():

    #args = parser.parse_args()

    BODY_PARTS = { "Nose": 0, "Neck": 1, "RShoulder": 2, "RElbow": 3, "RWrist": 4,
                "LShoulder": 5, "LElbow": 6, "LWrist": 7, "RHip": 8, "RKnee": 9,
                "RAnkle": 10, "LHip": 11, "LKnee": 12, "LAnkle": 13, "REye": 14,
                "LEye": 15, "REar": 16, "LEar": 17, "Background": 18 }

    POSE_PAIRS = [ ["Neck", "RShoulder"], ["Neck", "LShoulder"], ["RShoulder", "RElbow"],
                ["RElbow", "RWrist"], ["LShoulder", "LElbow"], ["LElbow", "LWrist"],
                ["Neck", "RHip"], ["RHip", "RKnee"], ["RKnee", "RAnkle"], ["Neck", "LHip"],
                ["LHip", "LKnee"], ["LKnee", "LAnkle"], ["Neck", "Nose"], ["Nose", "REye"],
                ["REye", "REar"], ["Nose", "LEye"], ["LEye", "LEar"] ]

    inWidth = 368#args.width
    inHeight = 368#args.height

    net = cv2.dnn.readNetFromTensorflow("graph_opt.pb")
    return [[BODY_PARTS,POSE_PAIRS],
            [inWidth,inHeight],
            net]

def func2(cap,V_list2):
    BODY_PARTS,POSE_PAIRS=V_list2[0]
    inWidth,inHeight=V_list2[1]
    net=V_list2[2]
    # exit=cv2.waitKey(1)
    # if exit&0xFF == ord('l'):
    #     return 
    # if exit&0xFF == ord('q'):
    #     return
    hasFrame, frame = cap.read()
    if not hasFrame:
        cv2.waitKey()
        return 

    frameWidth = frame.shape[1]
    frameHeight = frame.shape[0]

    net.setInput(cv2.dnn.blobFromImage(frame, 1.0, (inWidth, inHeight), (127.5, 127.5, 127.5), swapRB=True, crop=False))
    out = net.forward()
    out = out[:, :19, :, :]  # MobileNet output [1, 57, -1, -1], we only need the first 19 elements

    assert(len(BODY_PARTS) == out.shape[1])

    points = []
    cameraset = []
    for i in range(len(BODY_PARTS)):
        # Slice heatmap of corresponging body's part.
        heatMap = out[0, i, :, :]
        #print(heatMap)

        # Originally, we try to find all the local maximums. To simplify a sample
        # we just find a global one. However only a single pose at the same time
        # could be detected this way.
        _, conf, _, point = cv2.minMaxLoc(heatMap)
        x = (frameWidth * point[0]) / out.shape[3]
        cameraset.append(x)
        y = (frameHeight * point[1]) / out.shape[2]
        cameraset.append(y)
        
        # Add a point if it's confidence is higher than threshold.
        points.append((int(x), int(y)) if conf >  0.2 else None)

        #args.thr
    #古人图片
    '''image = np.array([293.65217391, 106.7826087 , 293.65217391, 173.52173913 ,240.26086957,
        186.86956522 ,240.26086957 ,293.65217391, 253.60869565 ,360.39130435,
        333.69565217, 173.52173913, 360.39130435, 280.30434783, 320.34782609,
        106.7826087 , 266.95652174 ,360.39130435 ,240.26086957 ,427.13043478,
        253.60869565, 440.47826087 ,333.69565217, 347.04347826 ,347.04347826,
        427.13043478 ,253.60869565 ,440.47826087, 280.30434783 ,106.7826087 ,
        293.65217391 , 93.43478261 ,280.30434783 ,106.7826087 , 320.34782609,
        106.7826087  ,587.30434783 , 13.34782609])'''

        #真人动作1
    '''image = np.array([550.95652174 ,180.7826087 , 568.17391304, 245.34782609, 602.60869565,
    245.34782609, 619.82608696, 284.08695652, 637.04347826, 271.17391304,
    533.73913043 ,245.34782609, 533.73913043, 297.00,         533.73913043,
    374.47826087, 533.73913043, 387.39130435, 533.73913043, 464.86956522,
    533.73913043, 555.26086957,568.17391304, 387.39130435, 585.39130435,
    477.7826087 , 533.73913043 ,581.08695652, 550.95652174, 167.86956522,
    568.17391304, 180.7826087,  550.95652174 ,193.69565217, 568.17391304,
    206.60869565 , 17.2173913 , 568.17391304])'''

    #真人动作2
    image = np.array([445.2173913,177.39130435,445.2173913,208.69565217,417.39130435,
                    208.69565217,389.56521739,250.43478261,417.39130435,260.86956522,
                    473.04347826,208.69565217,486.95652174,250.43478261,459.13043478,
                    396.52173913,459.13043478,469.56521739,445.2173913,177.39130435,
                    445.2173913,177.39130435,431.30434783,177.39130435,459.13043478,
                    177.39130435,17.2173913 , 568.17391304])
                    
    camera = np.array(cameraset) #一维数组转矩阵行向量
    #print(camera)
    vector_centerpoint(image)
    vector_centerpoint(camera)
    #print(vector_centerpoint(camera))
    #print(similarity(image,camera))
    flag = video_brodcast(image,camera)
    for pair in POSE_PAIRS:
        partFrom = pair[0]
        partTo = pair[1]
        assert(partFrom in BODY_PARTS)
        assert(partTo in BODY_PARTS)

        idFrom = BODY_PARTS[partFrom]
        idTo = BODY_PARTS[partTo]

        if points[idFrom] and points[idTo]:
            cv2.line(frame, points[idFrom], points[idTo], (0, 255, 0), 3)
            cv2.ellipse(frame, points[idFrom], (3, 3), 0, 0, 360, (0, 0, 255), cv2.FILLED)
            cv2.ellipse(frame, points[idTo], (3, 3), 0, 0, 360, (0, 0, 255), cv2.FILLED)

    t, _ = net.getPerfProfile()
    freq = cv2.getTickFrequency() / 1000
    cv2.putText(frame, '%.2fms' % (t / freq), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
    return frame,flag


